﻿//var dojoConfig = { parseOnLoad: true };
//dojo.require("esri.map");
//dojo.require("dijit.form.Button");
//dojo.require("dijit.layout.BorderContainer");
//dojo.require("dijit.layout.ContentPane");
//dojo.require("esri.dijit.BasemapGallery");
//dojo.require("esri.arcgis.utils");

//dojo.require("esri.layers.KMLLayer");
//dojo.require("dojox.mobile");

var wms_waterquality, wms_effectivearea, wms_resource,wms_Pipeline_age_15,wms_Pipe_line_age_15_to_25;
var wms_railway,wms_Main_pipe_age_15,wms_distribution_pipe_age_15, wms_pipe_AC_age_15;
var wms_Main_Pipe_age_15_to_25, wms_distribution_pipe_age_15_to_25,wms_pipe_AC_age_15_to_25;
var wms_pipe_line_age_25_to_30,wms_Main_pipe_age_25_to_30, wms_distribution_pipe_age_25_to_30;
var wms_pipe_ac_age_25_to_30,wms_pipe_line_age_over_30,wms_Main_pipe_age_over_30;
var wms_distribution_pipe_age_over_30, wms_pipe_ac_age_over_30, wms_tunnel_originel;
var wms_main_pipe_originel, wms_distribution_pipe, wms_region, wms_water_praya;
var wlma_status, wlma_NFA_Alert, wlma_p_wl, landuse;
var wms_crm1,wms_crm2,wms_crm3,wms_crm4;
var toplevel = 0;
var wms_order = [];
var map;
var geolocationMarker = 0;
var elevator;
var height = "";
var geocoder;
var wms_stolenmeter_2015_02,wms_stolenmeter_2015_03,wms_stolenmeter_2015_04,wms_stolenmeter_2015_05,wms_stolenmeter_2015_06;

// Real-time marker clusterers
var markerClusterer2;  
var cluster = [];
// Eservice marker clusterers
var cluster_eservice = [];
// Water Level marker clusterers
var cluster_waterlevel = [];
// Water Quality marker clusterers
var cluster_waterquality = [];
//GIS Camera Reporter current infobox
var reporter_ib;

var Long = 100.540094, Lat = 13.770899;
var gmap = null;
var weatherLayer, trafficLayer;
var markersArray = [];
var proxy = "./cgi-bin/proxy.php?";			// proxy for camera reporter kml
											// links
var cloudLayer;
var branch_prev, age_prev, wlma_branch_prev; // store current branch, age layer for radio button removal
var position_text;
//var car_path = [];			// store polyline of GISTDA car tracker
var car_position, car_timer; 

var Eserviceinfowindow = new google.maps.InfoWindow();
var GeoLocationInfowindow = new google.maps.InfoWindow();
var WaterQualityInfowindow = new google.maps.InfoWindow();
var WaterLevelInfowindow = new google.maps.InfoWindow();

currentFeature_or_Features = null;						// stores current Eservice markers on the map
var RtuMarkers = [];
var WaterQualityMarkers = [];
var WaterLevelMarkers = [];
var markerGISsreach = [];
var gisSearchInfo;
var monthText = {
    1 : "ม.ค. 58",
    2 : "ก.พ. 58",
    3 : "มี.ค. 58",
    4 : "เม.ย. 58",
    5 : "พ.ค. 58",
    6 : "มิ.ย. 58",
    7:  "ก.ค. 58",
    8:  "ส.ค. 58",
    9:  "ก.ย. 58",
    10:  "ต.ค. 58",
    11:  "พ.ย. 58",
    12:  "ธ.ค. 58"
        
};
var RemovePrevStolenMeter;				// function for removing previous stolen meter layer
var RemovePrevChlorine;					// function for removing previous chlorine contour layer
var monthWMS;
var eserviceDatePicker;						// mobipick object for eservice datepicker
var eserviceStatus;							// status of eservice checkbox
var isEserviceDatePickerClicked;
var directionsDisplay, directionsService, latlngGISSearch;
var Condo = [], SingleHouse = [], Townhouse = [];
function init() { 
    
    $.getJSON( "ajax/nameBranchGIS.php", function( nameBranch ) {//get json from service in gis and append value drpodown
        for (var i = 0; i < nameBranch.features.length; i ++) {
           var NAME = nameBranch.features[i].attributes.NAME;
           var DISTRICT_ID = nameBranch.features[i].attributes.DISTRICT_I;  
           //console.log(NAME, DISTRICT_ID);
           $("#list_branch").append('<option value="'+DISTRICT_ID+'">'+NAME+'</option>');
        }
      });
   
    // esri.config.defaults.io.proxyUrl = "proxy/proxy.php";
    // esri.config.defaults.io.alwaysUseProxy = "false";
    geocoder = new google.maps.Geocoder(); // geocoder for google geolocation
											// search
    var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(Lat, Long),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        // ROADMAP, HYBRID, TERRAIN, SATELLITE
        mapTypeControl: false,
        panControl: false,
        zoomControl: true,
        streetViewControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.DEFAULT,
            position: google.maps.ControlPosition.LEFT_CENTER
        }
        // streetViewControl : false //enable/disable Google street view
    };
    // google map
    map = new google.maps.Map(document.getElementById('map'), mapOptions); // show
    
    directionsService = new google.maps.DirectionsService();
    var rendererOptions = {
        map: map,
        suppressMarkers : true,
        polylineOptions: {
            strokeColor: "red"
        }
    };
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);																			// base
																			// map
///////////////////////////////////////////GoogleMapAutocomplese///////////////////////////////////////    
    var input = (document.getElementById('gsearch_address'));
	var autocomplete = new google.maps.places.Autocomplete(input);
	
	//Intitial_SearchGIS();//SearchGIS INITIAL 
	WMS_Call_Layers();//WMS INITIAL 
		
    // open street basemap
    map.mapTypes.set("OSM", new google.maps.ImageMapType({
        getTileUrl: function(coord, zoom) {
            return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
        },
        tileSize: new google.maps.Size(256, 256),
        name: "OpenStreetMap",
        maxZoom: 18
    }));
    elevator = new google.maps.ElevationService(); // google elevation service
    // ESRI world map
    var url1 = 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/';
    var agsType1 = new gmaps.ags.MapType(url1, {
        name: 'ArcGIS'
    });
    // MWA 1:1000 cache map
    var url = './cgi-bin/ba-simple-proxy.php?url=http://172.16.195.26/arcgis/rest/services/mobileCache/mobileCache/MapServer';
    var cache = new gmaps.ags.MapType(url, {
        name: 'Cache'
    });
	// ESRI Raster Service
    var url2 = './cgi-bin/arcgisproxy.php?http://antares.esri.cdg.co.th/arcgis/rest/services/MWA/RASTER/MapServer/';
    var raster = new gmaps.ags.MapType(url2, {
        name: 'raster'
    });
  
    map.mapTypes.set('esri', agsType1);
    map.mapTypes.set('cache', cache);
    map.mapTypes.set('raster', raster);
  
   
    var options = {
        center: [Long, Lat],
        basemap: "streets",
        // The following are valid options: "streets" , "satellite" , "hybrid",
		// "topo", "gray", "oceans", "national-geographic". As of version 3.3
        zoom: 8
    };
    // get elevation and longlat from mouse
    google.maps.event.addListener(map, 'click', function(event) {
        var positionalRequest = {
            'locations': [event.latLng]
        };
        getElevation(positionalRequest);
        long3 = event.latLng.lng().toFixed(3);
        lat3 = event.latLng.lat().toFixed(3);
        $("#longlatlabel").html(long3 + ", " + lat3 + height);
	getFeatureInfo(event.latLng);
    });
    google.maps.event.addListener(map, 'mousemove', function(event) {
        var positionalRequest = {
            'locations': [event.latLng]
        };
        getElevation(positionalRequest);
        long3 = event.latLng.lng().toFixed(3);
        lat3 = event.latLng.lat().toFixed(3);
        $("#longlatlabel").html(long3 + ", " + lat3 + height);
		
    });
	
	// google weather
    weatherLayer = new google.maps.weather.WeatherLayer({
        temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
    });
    // google cloud layer
    cloudLayer = new google.maps.weather.CloudLayer();
    // google traffic layer
    trafficLayer = new google.maps.TrafficLayer();
    // current user online count
    UserOnlineCount();
    // GIS camera reporter refresh
	var t = setInterval("refreshKml()", 20000); // refresh GIS Camera Reporter every 2min 
		
	$( "#report_popup iframe" )
        .attr( "width", 0 )
        .attr( "height", 0 );
	// array to map stolen meter slider value to the correct WMS
	monthWMS = {
            12 : { name : "stolenmeter_2014_12", wms : wms_stolenmeter_2014_12},
            1 : { name : "stolenmeter_2015_01", wms : wms_stolenmeter_2015_01},
            2 : { name : "stolenmeter_2015_02", wms : wms_stolenmeter_2015_02},
            3 : { name : "stolenmeter_2015_03", wms : wms_stolenmeter_2015_03},
            4 : { name : "stolenmeter_2015_04", wms : wms_stolenmeter_2015_04},
            5 : { name : "stolenmeter_2015_05", wms : wms_stolenmeter_2015_05},
            6 : { name : "stolenmeter_2015_06", wms : wms_stolenmeter_2015_06},
            8 : { name : "stolenmeter_2014_08", wms : wms_stolenmeter_2014_08},
            9 : { name : "stolenmeter_2014_09", wms : wms_stolenmeter_2014_09},
            10 : { name : "stolenmeter_2014_10", wms : wms_stolenmeter_2014_10},
            11 : { name : "stolenmeter_2014_11", wms : wms_stolenmeter_2014_11}
            
          
	};
	XDate.locales['th'] = {
		monthNames: ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'],
		monthNamesShort: ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'],
		dayNames: ['จันทร์','อังคาร','พุธ','พฤ','ศกร์','เสาร์','อาทิตย์'],
		dayNamesShort: ['จ.','อ.','พ.','พฤ.','ศ.','ส.','อา.']
	};
	eserviceDatePicker = $( ".datepicker").mobipick({
		maxDate: new XDate().addDays(-1),
		dateFormat: "yyyy-MM-dd",
		locale: "th"
	});
	
}
function OverlayStolenMeter(isSelected){
	var month = $("#month_slider").val() % 12;
        
	if (RemovePrevStolenMeter != null)
		RemovePrevStolenMeter();
	if (isSelected)
	{
		$(".stolenmeter").show();
		map.overlayMapTypes.insertAt(toplevel, monthWMS[month].wms);
		toplevel++;
		wms_order.push(monthWMS[month].name);
		RemovePrevStolenMeter = function(){
			index = wms_order.indexOf(monthWMS[month].name);
			map.overlayMapTypes.removeAt(index);
			toplevel--;
			ShiftArray(index);
		};
	}
	else
	{
		$(".stolenmeter").hide();
		RemovePrevStolenMeter = null;
	}
}
function OverlayChlorine(isSelected){
	var month = $("#chlorine_month_slider").val();
        
	if (RemovePrevChlorine != null)
		RemovePrevChlorine();
	if (isSelected)
	{
		$(".chlorine").show();
		Chlorine[month].obj.setMap(map);
		RemovePrevChlorine = function()
		{
			Chlorine[month].obj.setMap(null);
		};
	}
	else
	{
		$(".chlorine").hide();
		RemovePrevChlorine = null;
	}
}
function UpdateStolenMeterLabel(){
        var monthVal = $("#month_slider").val() % 12;
	var monthlabel = monthText[monthVal]; 
	$("#month_slider_text").text(monthlabel);
}
function UpdateChlorineLabel(){
        var monthVal = $("#chlorine_month_slider").val() % 12
	var month = monthText[monthVal]; 
	$("#chlorine_month_slider_text").text(month);
}
//cluster markers
function AddMarkersToCluster(marker_array){
	if (markerClusterer2 == null) {  // first time
		//console.log("first time", cluster, markerClusterer2);
		markerClusterer2 = new MarkerClusterer(map, marker_array);
	}
	else {	
		markerClusterer2.addMarkers(marker_array);
		markerClusterer2.redraw();
		//console.log("AddMarkersToCluster", marker_array.length, markerClusterer2.getTotalMarkers());
	}
}
function AddMarkerToCluster(marker){
	if (markerClusterer2 == null) {  // first time
		//console.log("first time", cluster, markerClusterer2);
		markerClusterer2 = new MarkerClusterer(map, marker);
	}
	else {	
		markerClusterer2.addMarker(marker);
		markerClusterer2.redraw();
		//console.log("AddMarkerToCluster", markerClusterer2.getTotalMarkers());
	}
}
//cluster eservice markers
function RemoveMarkerFromCluster(marker)
{
	//console.log("remove markers: ", marker);
	if (marker.length)
	{
		for (var i = 0; i < marker.length; i++)
		{
			markerClusterer2.removeMarker(marker[i]);
		}
		markerClusterer2.redraw();
		//console.log("removemarkerfromclusterer markerclusterer2:", markerClusterer2);
	}
}
// display kml from link for GIS Camera reporter kml links
// using library geoXML parser from ags.js to parse and refresh GIS Camera Reporter KMLs
function OverlayGisCameraRepoterKml(selected) {
	//console.log("OverlayGisCameraRepoterKml");
	if(selected == 'mainleak') {
		selectedLayer = serviceR[0];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo1 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo1;
		selectedLayer[3].parse(path);
	}
	if(selected == 'connect') {
		selectedLayer = serviceR[1];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo2 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo2;
		selectedLayer[3].parse(path);
	}
	if(selected == 'engproj') {
		selectedLayer = serviceR[2];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo3 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo3;
		selectedLayer[3].parse(path);
	}	
	if(selected == 'PR') {
		selectedLayer = serviceR[3];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo4 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo4;
		selectedLayer[3].parse(path);
	}	
	if(selected == 'mainraise')	{
		selectedLayer = serviceR[4];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo5 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo5;
		selectedLayer[3].parse(path);		
	}	
	if(selected == 'Eat')	{
			selectedLayer = serviceR[5];
			selectedLayer[1] = true;
			path = selectedLayer[2];
			geo6 = new geoXML3.parser({
				map: map,
				zoom: true,
				singleInfoWindow: true
				// infoWindow: infowindow
				// createMarker: createMarker
			});
			selectedLayer[3] = geo6;
			selectedLayer[3].parse(path);		
	}
	if(selected == 'Rtu')	{
			selectedLayer = serviceR[6];
			selectedLayer[1] = true;
			path = selectedLayer[2];
			geo7 = new geoXML3.parser({
				map: map,
				zoom: true,
				singleInfoWindow: true
				// infoWindow: infowindow
				// createMarker: createMarker
			});
			selectedLayer[3] = geo7;
			selectedLayer[3].parse(path);
					
	}
        if(selected == 'pipejacking')	{
                selectedLayer = serviceR[7];
		selectedLayer[1] = true;
		path = selectedLayer[2];
		geo3 = new geoXML3.parser({
			map: map,
			zoom: true,
			singleInfoWindow: true
			// infoWindow: infowindow
			// createMarker: createMarker
		});
		selectedLayer[3] = geo3;
		selectedLayer[3].parse(path);	
	}
	//console.log("in gjs.js", cluster.length);
	//AddMarkersToCluster(cluster);	
}

// hide kml from link for GIS Camera reporter kml links
 function HideGisCameraReporterKml(selected) {
	switch(selected) {
		case 'mainleak':
			serviceR[0][1] = false;
			serviceR[0][3].hideDocument();  // see geoxml3-modify:	 http://geocontext.org/pliki/2010/test-geoxml3/test2/geoxml3-modify.js
			serviceR[0][3] = null;
			// console.log("clear markers");
			break;
		case 'connect':
			serviceR[1][1] = false;
			serviceR[1][3].hideDocument(); 
			serviceR[1][3] = null;
			break;
		case 'engproj':
			serviceR[2][1] = false;
			serviceR[2][3].hideDocument();
			serviceR[2][3] = null;
			break;
		case 'PR':
			serviceR[3][1] = false;
			serviceR[3][3].hideDocument(); 
			serviceR[3][3] = null;
			break;
		case 'mainraise':
			serviceR[4][1] = false;
			serviceR[4][3].hideDocument(); 
			serviceR[4][3] = null;
			break;
		case 'Eat':
			serviceR[5][1] = false;
			serviceR[5][3].hideDocument(); 
			serviceR[5][3] = null;
			break;
		case 'Rtu':
			serviceR[6][1] = false;
			serviceR[6][3].hideDocument(); 
			serviceR[6][3] = null;
                        
			break;
                case 'pipejacking':
			serviceR[7][1] = false;
			serviceR[7][3].hideDocument(); 
			serviceR[7][3] = null;
                        
	}	
	
}
// get current elevation from google
function getElevation(positionalRequest) {
	elevator.getElevationForLocations(positionalRequest, function(results, status) {
		if (status == google.maps.ElevationStatus.OK) {
			// Retrieve the first result
			if (results[0]) {
				height = ", " + results[0].elevation.toFixed(3) + " m";
			} 
		} 
	});
}
// current user online count
function UserOnlineCount(){
	// console.log("counting users");
	var StartUserOnline = 0 ;
	if(StartUserOnline == 0) {                                                                 
		$.ajax({                    
			type: "POST",
			url: "UserOnline.php",                   
			data:{                            
				USER_ONLINE:"StartWebPage"                                                
			}}).done(function(data) {                                                          
			$("#UserOnline").html(data);
				StartUserOnline = 1;
				UserOnlineRealtime();                    
		}); 
	}
	function UserOnlineRealtime() {
		$(function(){                
			setInterval(function(){                 
				var getData=$.ajax({ 
					type: "POST",
					url:"UserOnline.php",
					data: {USER_ONLINE:"StartWebPage"} ,
					async:false,
					success:function(getData){
						$("#UserOnline").html(getData); 
					}
				}).responseText;
			},120000); // refresh user count every 2 minute
		});
	}      
}

function checkGeolocationSupport() {
		// Check if the browser supports geolocation
	if(navigator.geolocation) {
	
		navigator.geolocation.getCurrentPosition(function(position) {
     
			// create a new LatLng object for every position update
			var myLatLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude );
			position_text = "I am here";
			// define our custom marker image
			var image = new google.maps.MarkerImage(
				'css/images/bluedot_retina.png',
				null, // size
				null, // origin
				new google.maps.Point( 8, 8 ), // anchor (move to center of
												// marker)
				new google.maps.Size( 17, 17 ) // scaled size (required for
												// Retina display icon)
			);
			// user reverse geocode to get address
			geocoder.geocode({
				'latLng': myLatLng
			}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if (results[1]) {
						position_text = results[1].formatted_address;
						GeoLocationInfowindow.setContent(position_text);
						GeoLocationInfowindow.open(map, geolocationMarker);
						//console.log("open");
					} 
				} 
			});
			// then create the new marker
			geolocationMarker = new google.maps.Marker({
				flat: true,
				icon: image,
				map: map,
				optimized: false,
				position: myLatLng,
				title: position_text,
				visible: true
			});
			
			google.maps.event.addListener(geolocationMarker, 'click', function() {
				GeoLocationInfowindow.open(map, geolocationMarker);
			});
			
			// center map view on every pass
			map.setCenter( myLatLng );
			if(map.getZoom() < 17)
				map.setZoom(17);
			
		});
	} 
	else {	
		alert('The browser does not support geolocation');		
	}
}

// clear current markers from map
function clearOverlays() {
	for (var i = 0; i < markersArray.length; i++ ) {
		markersArray[i].setMap(null);
	}
	markersArray = [];
}
// resize map to fit screen on orientation change
function orientationChanged() {
	hideAddressBar();
	if (isiPhone != null) {
		// iPhone
		if (isPortrait) {
			// portrait ----> landscape mode
			adjustMapHeight();
			isPortrait = false;
		} 
		else {
			// landscape ----> portrait mode
			dojo.byId("map").style.height = (window.innerHeight + statusBarHeight) + "px";
			isPortrait = true;
		}
	} 
	else if (isiPad != null) {
			// iPad
		adjustMapHeight();
	}
	if (map) {
		map.resize();
		map.reposition();
	}
}
function adjustMapHeight() {
	dojo.byId("map").style.height = (window.innerHeight - headerGeom.h) + "px";
}
function hideAddressBar() {
	// Set a timeout...
	setTimeout(function () {
		// Hide the address bar!
		window.scrollTo(0, 1);
	}, 0);
}
function hideAddressBar() {
	if (navigator.userAgent.match(/Android/i)) {
		window.scrollTo(0, 0); // reset in case prev not scrolled
		var nPageH = $(document).height();
		var nViewH = window.outerHeight;
		if (nViewH > nPageH) {
			nViewH = nViewH / window.devicePixelRatio;
			$('BODY').css('height', nViewH + 'px');
		}
		window.scrollTo(0, 1);
	} else {
		addEventListener("load", function() {
			setTimeout(hideURLbar, 0);
			setTimeout(hideURLbar, 500);
		}, false);
	}

	function hideURLbar() {
		if (!pageYOffset) {
			window.scrollTo(0, 1);
		}
	}
	return this;
}
// close search pop
function closePopup(){
	$("#search_popup").popup( "close" );
}
// hide and display kml to refresh
// for GIS Camera Reporter
function refreshKml() {
	for(var i = 0; i < serviceR.length; i++) {
		if(serviceR[i][3] != null) {
			//console.log("REFRESH 1. hide markers and remove from cluster before:", cluster);
			RemoveMarkerFromCluster(cluster);
			cluster = [];
			serviceR[i][3].hideDocument();
			serviceR[i][3] = null;
			//console.log("2. overlay markers :", serviceR[i][0]);
			OverlayGisCameraRepoterKml(serviceR[i][0]);
		}
	}
}

function ClearOverlay_BY_JIK (Array) {
	for (var i = 0; i < Array.length; i++) 
		Array[i].setMap(null);
}


function ShiftArray(index)
{
	var Elements1 = wms_order.slice(0, index);
	var Elements2 = wms_order.slice(index+1);
	wms_order = Elements1.concat(Elements2);
	
}

function GetEservice(d,m,y){           
	//url = "https://eservices.mwa.co.th/gps/uploads/jobgis.php?"; //start=2014-09-22&end=2014-10-23";
	url = "AjaxEservice.php";
	start = new XDate(y,m,d);
	// Default date is yesterday
	tmp = start.clone();
	//  Start date is the day before end date;
	end = tmp.addDays(1);
	//console.log(start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd"));
	$.ajax({
		//dataType: "jsonp",
		type: "POST",
		url: url,
		data: {
				start: start.toString("yyyy-MM-dd"),
				end: end.toString("yyyy-MM-dd")
		},
		success: function (data) {   
			//console.log("SUCCESS");
			console.log(data, start.toString("yyyy-MM-dd"), end.toString("yyyy-MM-dd"));
                        //console.log(end.toString("yyyy-MM-dd"));
                        
			try
			{
				Points = $.parseJSON(data);
                                //console.log("Points = ", Points);
			}
			catch (error)
			{
				console.log("invalid JSON");
			}
			RemoveMarkerFromCluster(cluster_eservice);
			cluster_eservice = [];
			showGeoJson(Points);
			AddMarkersToCluster(cluster_eservice);
		},
		error: function (request, error){
			console.log("error", error);
		}
	});
	
}
function setEserviceInfoWindow (feature)	
{
	google.maps.event.addListener(feature, "click", function(event) {
            
                if(Eserviceinfowindow) {
                    Eserviceinfowindow.close();
                }
		var content = "<div id='infoBox'><strong>E-Service</strong><br />";
		for (var j in this.geojsonProperties) {
			content += j + ": " + this.geojsonProperties[j] + "<br />";
		}
		var image1 = this.geojsonProperties["ImagePath"];
		var image2 = image1.replace("1\.jpg", "2\.jpg");
		image2 = image2.replace('a ', 'a style=\"display:none;\" ');
		var image3 = image1.replace("1\.jpg", "3\.jpg");
		image3 = image3.replace('a ', 'a style=\"display:none;\" ');
		content += image2+image3;
		content += "</div>";
		Eserviceinfowindow.setContent(content);
		Eserviceinfowindow.position = feature.position;
		Eserviceinfowindow.open(map, this);
                
                //console.log(Eserviceinfowindow.position, event.latLng);
		var tag = "prettyPhoto["+ this.geojsonProperties["AccountID"]+"]";
		$("a[href$='.jpg']").attr( "rel", tag );
		//console.log($("a[href$='.jpg']"));
		//console.log($("a[rel^='prettyPhoto']:lt(3)"));
		setTimeout(function() {
			$("a[rel^='prettyPhoto']:lt(3)").prettyPhoto();
		}, 100);
		
		
	});
}
function showGeoJson(geojson)
{
	RemoveMarkerFromCluster(cluster_eservice);
	clearEservice();
	cluster_eservice = [];
	currentFeature_or_Features = new GeoJSON(geojson, {"icon": "http://gisonline.mwa.co.th/jb/geojson/house.png"});
	if (currentFeature_or_Features.length){
		for (var i = 0; i < currentFeature_or_Features.length; i++){
			if(currentFeature_or_Features[i].length){
				for(var j = 0; j < currentFeature_or_Features[i].length; j++){
					currentFeature_or_Features[i][j].setMap(map);
					cluster_eservice.push(currentFeature_or_Features[i][j]);
					if(currentFeature_or_Features[i][j].geojsonProperties) {
						setEserviceInfoWindow(currentFeature_or_Features[i][j]);
					}
				}
			}
			else{
				currentFeature_or_Features[i].setMap(map);
				cluster_eservice.push(currentFeature_or_Features[i]);
			}
			if (currentFeature_or_Features[i].geojsonProperties) {
				setEserviceInfoWindow(currentFeature_or_Features[i]);
			}
		}
	}
	else
	{
		if(currentFeature_or_Features.length)
		{
			currentFeature_or_Features.setMap(map);
			cluster_eservice.push(currentFeature_or_Features);
			if (currentFeature_or_Features.geojsonProperties) {
				setEserviceInfoWindow(currentFeature_or_Features);
                                
			}
		}
		
	}
	//console.log("finished overlay final cluster", cluster_eservice);
	
}
function clearEservice()
{
	if (!currentFeature_or_Features)
			return;
		if (currentFeature_or_Features.length){
			for (var i = 0; i < currentFeature_or_Features.length; i++){
				if(currentFeature_or_Features[i].length){
					for(var j = 0; j < currentFeature_or_Features[i].length; j++){
							currentFeature_or_Features[i][j].setMap(null);
					}
				}
				else{
					currentFeature_or_Features[i].setMap(null);
				}
			}
		}else{
			if(currentFeature_or_Features.length)
				currentFeature_or_Features.setMap(null);
		}
		if (Eserviceinfowindow.getMap()){
			Eserviceinfowindow.close();
		}
}
function callEserviceDatePicker()
{
	
	eserviceDatePicker.mobipick( "open" );
	eserviceDatePicker.on( "change", function() {
		//console.log("event on datepicker confirmation");
		// use the date after confirmation
			if (eserviceStatus == true)
			{
				// Refresh Eservice markers on date change
				dateString = eserviceDatePicker.mobipick("dateString");
				date = XDate.parse(dateString);
				date = new XDate(date);
				d = date.getDate();
				m = date.getMonth();
				y = date.getFullYear();
				GetEservice(d,m,y);
				
			}
		// or alternatively
		// window.alert( eserviceDatePicker.mobipick( "dateString" ) );
		// window.alert( eserviceDatePicker.mobipick( "localeString" ) );
	});
	
	
}
function OverlayWaterQuality(points){
	ClearOverlay_BY_JIK(WaterQualityMarkers);
	WaterQualityMarkers = [];
	//console.log(WaterQualityMarkers);
	$.each( points, function( index, value ) {
		var content = "";
		//console.log(index, value);
		var obj = value;
		$.each( obj, function( key, value ) {
			if (key == "station_lat")
				lat = value;
			else if (key == "station_lon")
				lon = value;
			else
				content += key +": " + value + "<br>";
		});
		var myLatlng = new google.maps.LatLng(lat,lon);
		var icon = "./image/WQ2.png";
		var label_text = points[index].conducted +", "+ points[index].salinity;
		label_text = label_text.replace(/&micro;S/, "µS");
		var mapLabel = new MapLabel({
	         text: label_text,
	         position: myLatlng,
	         map: map,
	         fontColor: '#ffd589',
	         strokeColor: '#7c5100',
	         fontSize: 14
		});
		var marker = new google.maps.Marker({
			position: myLatlng,
			map: map,
			title: "Water Quality",
			icon: icon
		});
		mapLabel.set('position', myLatlng);	       
        marker.bindTo('map', mapLabel);
        marker.bindTo('position', mapLabel);		           	      		
        WaterQualityMarkers.push(marker);
        
        google.maps.event.addListener(marker, 'click', function() {
			if (WaterQualityInfowindow){
				WaterQualityInfowindow.close();
			}
			WaterQualityInfowindow = new google.maps.InfoWindow({
				content : content,
				maxWidth: 1000,
				maxHeigth: 1000							 
			});	
			WaterQualityInfowindow.open(map, this);						
		});
		
	
	});
}
function OverlayWaterLevel(points){
	ClearOverlay_BY_JIK(WaterLevelMarkers);
	WaterLevelMarkers = [];
	//console.log(WaterQualityMarkers);
	$.each( points, function( index, value ) {
		var content = "";
		//console.log(index, value);
		var obj = value;
		$.each( obj, function( key, value ) {
			if (key == "probeLat")
				lat = value;
			else if (key == "probeLon")
				lon = value;
			else
				content += key +": " + value + "<br>";
		});
		//console.log(content);
		var myLatlng = new google.maps.LatLng(lat,lon);
		var icon = "./image/icon_WaterLevels.png";
		var mapLabel = new MapLabel({
	         text: points[index].Level,
	         position: myLatlng,
	         map: map,
	         fontColor: '#FAF8BD',
	         strokeColor: '#00000',
	         fontSize: 14
		});
		var marker = new google.maps.Marker({
			position: myLatlng,
			map: map,
			title: "Water Level",
			icon: icon
		});
		mapLabel.set('position', myLatlng);	       
        marker.bindTo('map', mapLabel);
        marker.bindTo('position', mapLabel);	           	      		
        WaterLevelMarkers.push(marker);
        google.maps.event.addListener(marker, 'click', function() {
			if (WaterLevelInfowindow){
				WaterLevelInfowindow.close();
			}
			WaterLevelInfowindow = new google.maps.InfoWindow({
				content : content,
				maxWidth: 1000,
				maxHeigth: 1000							 
			});	
			WaterLevelInfowindow.open(map, this);						
		});
		
	
	});
}
function GetWaterQuality()
{
	url = "AjaxWaterQuality.php";
	$.ajax({
		//dataType: "jsonp",
		type: "POST",
		url: url,
		success: function (data) {   
			console.log("SUCCESS");
			console.log(data);
			try
			{
				Points = $.parseJSON(data);
				OverlayWaterQuality(Points);
			}
			catch (error)
			{
				console.log("invalid JSON");
			}
		},
		error: function (request, error){
			console.log("error", error);
		}
	});
}

function GetWaterLevel()
{
	url = "AjaxWaterLevel.php";
	$.ajax({
		type: "POST",
		url: url,
		success: function (data) {   
			//console.log("SUCCESS");
			//console.log(data);
			try
			{
				Points = $.parseJSON(data);
                                console.log(data);
				OverlayWaterLevel(Points);
			}
			catch (error)
			{
				console.log("invalid JSON");
			}
		},
		error: function (request, error){
			console.log("error", error);
		}
	});
}
//Get Thai name of graph report function
function GetGraphName(graphcode){
    var graphname;
    if(graphcode=="BACKOFFICE_Q_PIPETUNNEL"){
        graphname="รายงานความยาวท่ออุโมงค์";
    }else if(graphcode=="BACKOFFICE_Q_PIPEMAIN"){
        graphname="รายงานความยาวท่อประทาน";
    }else if(graphcode=="BACKOFFICE_Q_PIPEDIS"){
        graphname="รายงานความยาวท่อจ่ายน้ำ";
    }else if(graphcode=="BACKOFFICE_Q_PIPEDIS_AGE"){
        graphname="รายงานอายุท่อจ่ายน้ำ";
    }else if(graphcode=="BACKOFFICE_Q_PIPETUNNEL_AGE"){
        graphname="รายงานอายุท่ออุโมงค์";
    }else if(graphcode=="BACKOFFICE_Q_PIPEMAIN_AGE"){
        graphname="รายงานอายุท่อประทาน";
    }else if(graphcode=="BACKOFFICE_Q_BRANCHAREA"){
        graphname="รายงานพื้นที่บริการ";
    }else if(graphcode=="BACKOFFICE_Q_FH"){
        graphname="รายงานจำนวนหัวดับเพลิง";
    }else if(graphcode=="BACKOFFICE_Q_VALVE"){
        graphname="รายงานจำนวนประตูน้ำ";
    }else{
        graphname="รายงานจำนวนจุดแตกรั่ว";
    }
    
   return graphname;
}
//Get branch name from branch code
function GetBranchName(branchcode){
    var branchname;
    
    if(branchcode=="01"){
        branchname="บางกอกน้อย";        
    }else if(branchcode=="02"){
        branchname="ตากสิน";
    }else if(branchcode=="03"){
        branchname="พญาไท";
    }else if(branchcode=="04"){
        branchname="นนทบุรี";
    }else if(branchcode=="05"){
        branchname="ทุ่งมหาเมฆ";
    }else if(branchcode=="06"){
        branchname="แม้นศรี";
    }else if(branchcode=="07"){
        branchname="สุขุมวิท";
    }else if(branchcode=="11"){
        branchname="ภาษีเจริญ";
    }else if(branchcode=="12"){
        branchname="ลาดพร้าว";
    }else if(branchcode=="13"){
        branchname="พระโขนง";
    }else if(branchcode=="14"){
        branchname="สุขสวัสดิ์";
    }else if(branchcode=="15"){
        branchname="ประชาชื่น";
    }else if(branchcode=="16"){
        branchname="บางเขน";
    }else if(branchcode=="17"){
        branchname="สมุทรปราการ";
    }else if(branchcode=="53"){
        branchname="มีนบุรี";
    }else if(branchcode=="54"){
        branchname="บางบัวทอง";
    }else if(branchcode=="55"){
        branchname="สุวรรณภูมิ";
    }else if(branchcode=="56"){
        branchname="มหาสวัสดิ์";
    }
    
    return branchname;
   
}
function GetCarPath()
{
	$.ajax({
		url: "rest/gistda_car.php",
		success : function(data){
			overlayCarPath(data);
		}
	});
}
function overlayCarPath(data)
{
	//var path = [];			// store lon/lat positions
	var position_array = $.parseJSON(data);
	// To Overlay Path
	/*
	for (var i = 0; i < position_array.length; i++)
	{
		// convert HHMM.MMMM to decimal 
		var dd = parseFloat(position_array[i].lat.substring(0,2));
		var mm_mmmm = parseFloat(position_array[i].lat.substring(2,9));
		var lat = dd + (mm_mmmm / 60);
		var dd = parseFloat(position_array[i].lon.substring(0,3));
		var mm_mmmm = parseFloat(position_array[i].lon.substring(3,10));
		var lon = dd + (mm_mmmm / 60);
		if (lat != 0 || lon != 0)
		{
			var position = new google.maps.LatLng(lat, lon);
			path.push(position);
		}
		
		
	}
	*/
	//console.log(position_array);
	var dd = parseFloat(position_array[0].lat.substring(0,2));
	var mm_mmmm = parseFloat(position_array[0].lat.substring(2,9));
	var lat = dd + (mm_mmmm / 60);
	var dd = parseFloat(position_array[0].lon.substring(0,3));
	var mm_mmmm = parseFloat(position_array[0].lon.substring(3,10));
	var lon = dd + (mm_mmmm / 60);
	var position = new google.maps.LatLng(lat, lon);
	if (car_position != null)
	{
		car_position.setMap(null);
		//car_path.setMap(null);
	}
	car_position = new google.maps.Marker({
		position: position,
		map: map,
		title: 'Car Position',
		icon: "image/car_pin.png"
	});
	// Construct the path line.
	/*
	car_path = new google.maps.Polyline({
		path: path,
		geodesic: true,
		strokeColor: '#d25e01',
		strokeOpacity: 1.0,
		strokeWeight: 2
	});
	car_path.setMap(map);
	*/

}
$(document).ready(function() { 
	function detectEvent(e) {
		// console.log('Current Event is: ' + e.type);
	}
	//close report popup
	$("#close_btn").click(function(){
		$('#report_popup').popup("close");
		//console.log("close");
		
	});
        $( "#report_popup_result" ).bind({
            popupbeforeposition: function(event, ui) {
                //alert("Call ajax");
                //Get value of graph select from dropdown
                var graph = $("#graph_select").val();
                
                //Get value of branch zone and block from dropdown
                var branch = $("#branch_select").val();
                var zone = $("#zone_select").val();
                var block = $("#block_select").val();
                
                //Query string variable for json 
                var str_branch = "";
                var str_zone = "";
                var str_block = "";
                             
                // Get JSON data from call_service 
                $.ajax({
                    url: "servicegraph/call_service.php",
                    type: "POST",
                    dataType: 'json',
                    data:{GRAPH_SELECT : graph},
                    success : function (result) {
                        //console.log(result.data);
                        
                        // set query command from dropdown
                        if(branch==""){
                                str_branch = "";
                                str_zone = "";
                                str_block = "";
                        }else{
                                if(branch!=null && zone==null && block==null){
                                        str_branch = " $.BRANCH =="+branch;
                                }else if(branch!= null && zone=="" && block==null){
                        		str_branch = " $.BRANCH =="+branch;
                         	}else if(branch!=null && zone!=null && block==""){
                                        str_branch = " $.BRANCH =="+branch;
                                        if(branch!=null && zone!=""){
                                                str_zone = " && $.ZONE =="+zone;
                                        }
                                }else{
                                        str_branch = " $.BRANCH =="+branch;
                                        str_zone = " && $.ZONE =="+zone;
                                        str_block = " && $.BLOCK =="+block;
                                }
                        }
                        var select = str_branch+str_zone+str_block;
                            console.log(select);
                            
                        // Linq library command to query data from json
                        var queryResult = $.Enumerable.From(result.data)
                            //.Where("$.BRANCH == 56 && $.ZONE == 01")
                            .Where(select)
                            //.Select("$.BRANCH + ':' + $.ZONE + ':' + $.BLOCK")
                            .ToArray();
                    
                        //Check retrieved data
                        console.log(queryResult);
                        console.log("Graph: "+graph+"Graph Name: "+GetGraphName(graph));
                        console.log("DMA: "+branch+':'+zone+':'+block);                                           
                        
                        //Set sub-title for graph  
                        var branch_subtitle;
                        var zone_subtitle;
                        var block_subtile;

                        if(branch==""){
                            branch_subtitle ="พื้นที่ สาขาทั้งหมด" 
                        }else{                            
                            branch_subtitle ='พื้นที่ สำนักงานประปาสาขา:'+ branch+'('+GetBranchName(branch)+')';
                        }             
                        if(zone=="" || zone==null){
                            zone_subtitle='';             
                        }else{
                            zone_subtitle=' Zone:'+zone ;
                        }                           
                        if(block=="" || block==null){
                            block_subtile='';                           
                        }else{
                            block_subtile=' Block:'+block ;
                        }
                        console.log(branch_subtitle);
                        console.log(zone_subtitle);
                        console.log(block_subtile);
                                                
                        //Check graph selection from user
                        //User selects pipe length graph
                        if(graph=="BACKOFFICE_Q_PIPETUNNEL" || graph=="BACKOFFICE_Q_PIPEMAIN" || graph=="BACKOFFICE_Q_PIPEDIS"){
                            //Groupby with SUM 
                            var graphResult = $.Enumerable.From(queryResult).GroupBy("$.MATL", null,
                            function (MATL, s) {
                                var result = {
                                    Material: MATL,
                                    TotalLength: s.Sum("$.LENGTH")
                                }
                                return result;
                            }).ToArray();
                            console.log(graphResult);

                            var material=[];
                            var length=[];
                            //put data from query to array
                            $.each( graphResult, function( index, val ){
                                 material.push(val.Material);
                                 length.push(val.TotalLength);
                            });

                            console.log(material);
                            console.log(length);
                                                                                                 
                            //HighChart Output
                            Highcharts.setOptions({
                                lang: {
                                    decimalPoint: '.',
                                    thousandsSep: ','
                                }
                                //colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
                            });

                            $('#report_popup_result').highcharts({
                                chart: {
                                    type: 'bar'
                                },
                                title: {
                                    text: 'Graph: '+ GetGraphName(graph)
                                },
                                subtitle: {
                                    //text: 'พื้นที่ สำนักงานประปาสาขา: '+branch+' ('+GetBranchName(branch)+')'+' Zone:'+zone+' Block:'+block
                                    text: branch_subtitle+zone_subtitle+block_subtile
                                },
                                xAxis: {
                                    //categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania']
                                    categories: material,
                                    title: {
                                        text: 'Material'
                                    }
                                },
                                yAxis: {
                                    min: 0,
                                    title: {
                                        text: 'Length (meters)',
                                        align: 'high'
                                    },
                                    labels: {
                                        overflow: 'justify'
                                    }
                                },
                                tooltip: {
                                    valueDecimals: 2,
                                    //valueSuffix: ' meters',
                                    pointFormat: "ความยาวท่อ: {point.y:,.2f} meters"
                                },
                                plotOptions: {
                                    bar: {
                                        dataLabels: {
                                            enabled: true,
                                            format: '{point.y:,.2f} m'
                                        }
                                    }
                                },
                                legend: {
                                    layout: 'vertical',
                                    align: 'right',
                                    verticalAlign: 'top',
                                    x: -50,
                                    y: 100,
                                    floating: true,
                                    borderWidth: 1,
                                    backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                                    shadow: true
                                },
                                credits: {
                                    enabled: false
                                },
                                series: [{
                                    name: 'Pipe',
                                    data: length
                                    //data: [107, 31, 635, 203, 2]
                                }]
                            });  
                        //User selects pipe age graph   
                        }else if(graph=="BACKOFFICE_Q_PIPEDIS_AGE" || graph=="BACKOFFICE_Q_PIPETUNNEL_AGE" || graph=="BACKOFFICE_Q_PIPEMAIN_AGE"){
                            
                            console.log("Pipe Age");
                            //Groupby with SUM 
                            var graphResult = $.Enumerable.From(queryResult).GroupBy("$.AGE", null,
                            function (AGE, s) {
                                var result = {
                                    Age: AGE,
                                    TotalLength: s.Sum("$.LENGTH")
                                }
                                return result;
                            }).ToArray();
                            
                            //sort data by age
                            var graphResultOrdered = $.Enumerable.From(graphResult).OrderBy("$.Age").ToArray();
                            
                            console.log(graphResultOrdered);

                            var age=[];
                            var length=[];
                            //put data from query to array
                            $.each(graphResultOrdered, function( index, val ){
                                 age.push(val.Age);
                                 length.push(val.TotalLength);
                            });

                            console.log(age);
                            console.log(length);
                            
                            //HighChart Output
                            Highcharts.setOptions({
                                lang: {
                                    decimalPoint: '.',
                                    thousandsSep: ','
                                }
                                //colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
                            });

                            $('#report_popup_result').highcharts({
                                chart: {
                                    type: 'column'
                                },
                                title: {
                                    text: 'Graph: '+ GetGraphName(graph)
                                },
                                subtitle: {
                                    //text: 'พื้นที่ สำนักงานประปาสาขา:'+branch+' ('+GetBranchName(branch)+')'+' Zone:'+zone+' Block:'+block
                                    text: branch_subtitle+zone_subtitle+block_subtile
                                },
                                xAxis: {
                                    //categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania']
                                    categories: age,
                                    title: {
                                        text: 'Pipe age'
                                    }
                                },
                                yAxis: {
                                    min: 0,
                                    title: {
                                        text: 'Length (meters)',
                                        align: 'high'
                                    },
                                    labels: {
                                        overflow: 'justify'
                                    }
                                },
                                tooltip: {
                                    valueDecimals: 2,
                                    //valueSuffix: ' meters',
                                    pointFormat: "ความยาวท่อ: {point.y:,.2f} meters"
                                },
                                plotOptions: {
                                    bar: {
                                        dataLabels: {
                                            enabled: true,
                                            format: '{point.y:,.2f} m'
                                        }
                                    }
                                },
                                legend: {
                                    layout: 'vertical',
                                    align: 'right',
                                    verticalAlign: 'top',
                                    x: -50,
                                    y: 100,
                                    floating: true,
                                    borderWidth: 1,
                                    backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                                    shadow: true
                                },
                                credits: {
                                    enabled: false
                                },
                                series: [{
                                    name: 'Pipe',
                                    data: length,
                                    //data: [107, 31, 635, 203, 2]
                                }]
                            });  
                        //User sellects branch area graph    
                        }else if(graph=="BACKOFFICE_Q_BRANCHAREA"){
                            console.log("Branch Area");
                            console.log(result.data);
                        //User sellects Fire Hydrant,Valve,Leak point graph      
                        }else{
                            //Fire Hydrant,Valve,Leak point
                            console.log("Out of graph");
                        }
                      


                        //$( "#report_popup_result" ).html('<h1>Highcharts Trellis chart emulation</h2><table id="trellis"><tr><td class="first"></td><td></td><td></td><td></td></tr></table>');
                   }
               

                });
                
            }
         });

        //detect graph menu change
        $("#graph_select").change(function() {
            //Reset Zone, Block dropdowns
            var zone_result = '<option value="" selected="selected" > ---- เลือก Zone ---- </option>';
            $('#zone_select').html(zone_result);
            
            var block_result = '<option value="" selected="selected" > ---- เลือก Block ---- </option>';
            $('#block_select').html(block_result);
            
            
             //Ajax to call branch data
            $.ajax({
                url: "servicegraph/combobox/combobox_branch.php",
                success : function (data) {
                    console.log(data);
                    //zone = $.parseJSON(data);
                    var branch_result = data
                    $('#branch_select').html(branch_result);
                    //Refresh dropdown
                    $("#branch_select").selectmenu('refresh');
                    $("#zone_select").selectmenu('refresh');
                    $("#block_select").selectmenu('refresh');
               }
           });           
        });
        
        //detect branch menu change
        $("#branch_select").change(function() {
            //Reset Block dropdowns
            var block_result = '<option value="" selected="selected" > ---- เลือก Block ---- </option>';
            $('#block_select').html(block_result);
            
           
            //Get value of branch from branch dropdown
            var branch = $("#branch_select").val();
            
             //Ajax to call zone data
            $.ajax({
                url: "servicegraph/combobox/combobox_zone.php",
                type: "POST",
                data:{BRANCH_ID : branch},
                success : function (data) {
                    console.log(data);
                    //zone = $.parseJSON(data);
                    var zone_result = data;
                    $('#zone_select').html(zone_result);
                    //Refresh dropdown
                    $("#zone_select").selectmenu('refresh');
                    $("#block_select").selectmenu('refresh');
               }
           });         
        });
        
        //detect zone menu change
        $("#zone_select").change(function() {
                     
            //Get value of branch and zone from branch dropdown
            var branch = $("#branch_select").val();
            var zone = $("#zone_select").val();
            
             //Ajax to call zone data
            $.ajax({
                url: "servicegraph/combobox/combobox_block.php",
                type: "POST",
                data:{BRANCH_ID : branch,ZONE_ID : zone},
                success : function (data) {
                    console.log(data);
                    //zone = $.parseJSON(data);
                    var block_result = data;
                    $('#block_select').html(block_result);
                    //Refresh dropdown
                    $("#block_select").selectmenu('refresh');
               }
           });   
        });
	
	// select basemap
	$( "input.popup_basemap2" ).on( "click", function() {		
		// console.log("clicked");
		//console.log( $("input.popup_basemap2:checked").val());
		var selected = $("input.popup_basemap2:checked").val();
		if (selected == 'hybrid'){
			map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		}
		else if (selected == 'streets'){
			map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		}
		else if (selected == 'openstreet'){
			map.setMapTypeId("OSM");
		}
		else if (selected == 'esri'){
			map.setMapTypeId('esri');
		}
		else if (selected == 'cache'){
			if(map.getZoom() < 10)
				map.setZoom(10);
			map.setMapTypeId('cache');
			
		}
		else if ( selected == 'raster' ) {
			if(map.getZoom() < 12)
				map.setZoom(12);
			map.setMapTypeId('raster');
		}
		else if ( selected == 'thaichote' ) {
			map.setMapTypeId('theos');
		}
	});
	$('#geolocation').click(  function(){
		if(!geolocationMarker)
			checkGeolocationSupport();
		// remove geolocationMarker on click 
		else {
			geolocationMarker.setMap(null);
			geolocationMarker = 0;
			GeoLocationInfowindow.close();
		}
	});
	$( "input.engineering_kml" ).on( "click", function() {  		//turn on/off engineering layer
		var selectedLayer = $(this).val();
		if ( toplevel <= 0 ) {
			toplevel = 0;
		}
                console.log(selectedLayer);
		 // Add remove KMLs
		if($(this).prop("checked"))
                    engineering[selectedLayer].obj.setMap(map);
                else
                    engineering[selectedLayer].obj.setMap(null);
		
	

		
	});
        $( "input.wms_crm" ).on( "click", function(e) {
            var selectedLayer = $(this).val();
            if (selectedLayer == "crm1") {	
                if($(this).prop("checked")) {					
                    map.overlayMapTypes.insertAt(toplevel, wms_crm1);
                    toplevel++;
                    wms_order.push("wms_crm1");
                }
                else {					
                    index = wms_order.indexOf("wms_crm1");
                    map.overlayMapTypes.removeAt(index);
                    toplevel--;		
                    ShiftArray(index);
                }
            }
            else if (selectedLayer == "crm2") {	
                if($(this).prop("checked")) {					
                    map.overlayMapTypes.insertAt(toplevel, wms_crm2);
                    toplevel++;
                    wms_order.push("wms_crm2");
                }
                else {					
                    index = wms_order.indexOf("wms_crm2");
                    map.overlayMapTypes.removeAt(index);
                    toplevel--;		
                    ShiftArray(index);
                }
            }
            else if (selectedLayer == "crm3") {	
                 if($(this).prop("checked")) {					
                    map.overlayMapTypes.insertAt(toplevel, wms_crm3);
                    toplevel++;
                    wms_order.push("wms_crm3");
                }
                else {					
                    index = wms_order.indexOf("wms_crm3");
                    map.overlayMapTypes.removeAt(index);
                    toplevel--;		
                    ShiftArray(index);
                }
            }
            else if (selectedLayer == "crm4") {	
                if($(this).prop("checked")) {					
                    map.overlayMapTypes.insertAt(toplevel, wms_crm4);
                    toplevel++;
                    wms_order.push("wms_crm4");
                }
                else {					
                    index = wms_order.indexOf("wms_crm4");
                    map.overlayMapTypes.removeAt(index);
                    toplevel--;		
                    ShiftArray(index);
                }
            }
        });
	$( "input.waterresource_checkbox" ).on( "click", function(e) {		// turn
																		// water
																		// resource
																		// layer
																	// on/off		
		var selectedLayer = $(this).val();
		if (selectedLayer == "waterlevel") {								
		// display 3 kmls for waterlevel
			if($(this).prop("checked")) {
				waterresource["riverstation"].obj.setMap(map);
				waterresource["waterlevel"].obj.setMap(map);
				waterresource["waterlevel1"].obj.setMap(map);
			}
			else {
				waterresource["riverstation"].obj.setMap(null);
				waterresource["waterlevel"].obj.setMap(null);
				waterresource["waterlevel1"].obj.setMap(null);
			}
		}
		else if (selectedLayer == 'gas') {
			if($(this).prop("checked")) {
				waterresource["ngv"].obj.setMap(map);
				waterresource["lpg"].obj.setMap(map);
			}
			else{
				waterresource["ngv"].obj.setMap(null);
				waterresource["lpg"].obj.setMap(null);
			}
		}
		else if (selectedLayer == "globalcloud") {
			if($(this).prop("checked"))			
				cloudLayer.setMap(map);			
			else			
				cloudLayer.setMap(null);			
		}
		else if (selectedLayer == "weather") {
			if($(this).prop("checked"))		
				weatherLayer.setMap(map);			
			else			
				weatherLayer.setMap(null);			
		}
		else if (selectedLayer == "traffic") {
			if($(this).prop("checked"))	
				trafficLayer.setMap(map);
			else				
				trafficLayer.setMap(null);
		}
		else if (selectedLayer == "cctv") {
			if($(this).prop("checked"))
				CCTV_IMAEG_BY_MiNiJIK ();			
			else
				ClearOverlay_BY_JIK(Array_cctv);			
		}
		else if (selectedLayer == "events") {
			if( $(this).prop("checked") )
				Event();			
			else
				ClearOverlay_BY_JIK(Array_Events);			
		}
		else if (selectedLayer == "Rtu")
		{
			if( $(this).prop("checked") ) {				
				if (map.zoom < 12) {
					map.setZoom(12);
				}
				GetRtu();
			}
			else {
				clearInterval(RtuTimer);
				ClearOverlay_BY_JIK(RtuMarkers);				
			}
		}
		else if ( selectedLayer == "chloringcontour") {
			if($(this).prop("checked")) 
				waterresource["contour"].obj.setMap(map);
			else
				waterresource["contour"].obj.setMap(null);
		}
		else if ( selectedLayer == "chlorineonline" ) {
			if($(this).prop("checked")){
				if (map.zoom < 12) {
					map.setZoom(12);
				}
								
				wqconline();		
				
			}
			else { 
				$("#LogtimeWQC").hide();
				ClearOverlay_BY_JIK(wqcMarkers);
			}
		}
		else if ( selectedLayer == "eservice" ) {
                        
			if (isEserviceDatePickerClicked == true)
			{
                            if (eserviceStatus == true)
                                    $(this).prop("checked", true);
                            else
                                    $(this).prop("checked", false);
                            isEserviceDatePickerClicked = false;
			}
			if($(this).prop("checked"))
			{
                            setTimeout(function(){
                                callEserviceDatePicker();
                            }, 50);
                            $( '#waterresource_popup' ).popup("close");
                            dateString = eserviceDatePicker.mobipick("dateString");
                            if (dateString == "")
                            {
                                    // call to overlay Eservice marker for the first time
                                    // default date is yesterday
                                    date = new XDate().addDays(-1);
                                    d = date.getDate();
                                    m = date.getMonth();
                                    y = date.getFullYear();
                                    // call function to get eservice 
                                    GetEservice(d,m,y);
                            }
                            //else
                            //{
                            //	date = XDate.parse(dateString);
                            //	date = new XDate(date);
                            //	d = date.getDate();
                            //	m = date.getMonth();
                            //	y = date.getFullYear();
                            //	console.log(d,m,y);
                            //}
				
			}
			else {
                            clearEservice();
                            RemoveMarkerFromCluster(cluster_eservice);
                            cluster_eservice = [];
                            // reset date on checkbox clear
                            eserviceDatePicker.mobipick("option", "date", null).mobipick("updateDateInput");
                            //$( '#waterresource_popup' ).on( 'popupafterclose', function() { console.log("unbind"); return false;	});
			}
			
		}
		else if (selectedLayer == "bangkok") {
			if($(this).prop("checked")) {					
				map.overlayMapTypes.insertAt(toplevel, wms_lup_2556);
				toplevel++;
				wms_order.push("wms_lup_2556");
			}
			else {					
				index = wms_order.indexOf("wms_lup_2556");
				map.overlayMapTypes.removeAt(index);
				toplevel--;		
				ShiftArray(index);
			}
		}
		// แผนที่คุณภาพน้ำคลองประปา Online
		else if ( selectedLayer == "canalquality" ) {
			if($(this).prop("checked")){
				GetWaterQuality();		
			}
			else { 
				ClearOverlay_BY_JIK(WaterQualityMarkers);
			}
		}
		// แผนที่ระดับน้ำ Online
		else if ( selectedLayer == "waterlevel2" ) {
			if($(this).prop("checked")){
				GetWaterLevel();	
			}
			else { 
				ClearOverlay_BY_JIK(WaterLevelMarkers);
			}
		}
		// Open KML
		else {
			if($(this).prop("checked"))
				waterresource[selectedLayer].obj.setMap(map);						
			else			
				waterresource[selectedLayer].obj.setMap(null);			
		}
	});
	
	$(".group_title").on("click", function(){
		//console.log("collapse clicked ");
		setTimeout(function () {
			$(".overflow_popup").popup("reposition", {positionTo: 'window'});
		}, 10);
		
	});
	$( "input.service_kml" ).on( "click", function() { 		// turn GIS Camera Reporter KML on/off
		var selectedLayer = $(this).val();
		if($(this).prop("checked"))	// display selected layer
		{
			OverlayGisCameraRepoterKml(selectedLayer);		
		}
		else
		{
			//console.log("1. hide on decheck");
			HideGisCameraReporterKml(selectedLayer);
			//console.log("2. remove from cluster", cluster);
			RemoveMarkerFromCluster(cluster);
			cluster = [];
		}
	});
	$( "input.branch_kml" ).on( "click", function() {		// turn engineering_kml branch kml on/off
		var branch = $(this).val();
		// console.log(branch);
		
		if(branch == "tunnel_originel") {
			if($(this).prop("checked")) {					
				map.overlayMapTypes.insertAt(toplevel, wms_tunnel_originel);
				toplevel++;
				wms_order.push("wms_tunnel_originel");
			}
			else {					
				index = wms_order.indexOf("wms_tunnel_originel");
				map.overlayMapTypes.removeAt(index);
				toplevel--;		
				ShiftArray(index);
			}
		}
		else if(branch == "Main_pipe_origenal") {
			if($(this).prop("checked")) {					
				map.overlayMapTypes.insertAt(toplevel, wms_main_pipe_originel);
				toplevel++;
				wms_order.push("wms_main_pipe_originel");
			}
			else {					
				index = wms_order.indexOf("wms_main_pipe_originel");
				map.overlayMapTypes.removeAt(index);
				toplevel--;		
				ShiftArray(index);
			}
		}
		else if(branch == "distribution_pipe") {
			if($(this).prop("checked")) {					
				map.overlayMapTypes.insertAt(toplevel, wms_distribution_pipe);
				toplevel++;
				wms_order.push("wms_distribution_pipe");
			}
			else {					
				index = wms_order.indexOf("wms_distribution_pipe");
				map.overlayMapTypes.removeAt(index);
				toplevel--;		
				ShiftArray(index);
			}
		}
		else if(branch == "region") {
			if($(this).prop("checked")) {					
				map.overlayMapTypes.insertAt(toplevel, wms_region);
				toplevel++;
				wms_order.push("wms_region");
			}
			else {					
				index = wms_order.indexOf("wms_region");
				map.overlayMapTypes.removeAt(index);
				toplevel--;		
				ShiftArray(index);
			}
		}
		
		/*if(branch_prev == branch){										// deselect radio button on second click
			$(this).prop('checked', false);
			for (var i = 0; i < branch_array[branch_prev].length; i++){		// remove previous branch KMLs
				branch_array[branch_prev][i].setMap(null);
			}
			branch_prev = null;
		}
		else if(branch_prev != null)												// remove previous branch before new overlay
		{
			for (var i = 0; i < branch_array[branch_prev].length; i++){		// remove previous branch KMLs
				branch_array[branch_prev][i].setMap(null);
			}
			for (var i = 0; i < branch_array[branch].length; i++){			// overlay all kmls in the selected branch
				branch_array[branch][i].setMap(map);
			}
			branch_prev = branch; 	
		}
		else{																// first time overlaying KML
			for (var i = 0; i < branch_array[branch].length; i++){			// overlay all kmls in the selected branch
				branch_array[branch][i].setMap(map);
			}
			branch_prev = branch; 											// add current branch to memory for removal
		}*/
	});

	$( "input.select_pipe_age" ).on( "click", function() {
		var age = $(this).val();
	/*	if (age_prev == age)									// deselect radio button on second click and remove overlay
		{
			$(this).prop('checked', false);
			//remove layer
			index = wms_order.indexOf(age_prev);				
			map.overlayMapTypes.removeAt(index);	
			toplevel--;	
			ShiftArray(index);
			//age_prev = null;
		}
		else if(age_prev != null)									// remove previous layer before overlaying
		{
			//remove layer
			index = wms_order.indexOf(age_prev);
			map.overlayMapTypes.removeAt(index);
			toplevel--;		
			ShiftArray(index);
			//overlay layer
			if (age == "pipe_age_15")
			{				
				map.overlayMapTypes.insertAt(toplevel, wms_Pipeline_age_15);
				toplevel++;
				wms_order.push("wms_Pipeline_age_15");
			}
			if (age == "pipe_age_25")
			{
				map.overlayMapTypes.insertAt(toplevel, wms_pipe_age_25);
				toplevel++;
				wms_order.push("pipe_age_25");
			}
			if (age == "pipe_age_30")
			{
				map.overlayMapTypes.insertAt(toplevel, wms_pipe_age_30);
				toplevel++;
				wms_order.push("pipe_age_30");
			}
			age_prev = age;										// add current age to memory for removal
		}*/
		//else{	
		// first time overlaying layer
		
			if (age == "pipe_line_age_15") {
				if($(this).prop("checked")) {					
					map.overlayMapTypes.insertAt(toplevel, wms_Pipeline_age_15);
					toplevel++;
					wms_order.push("wms_Pipeline_age_15");
				}
				else {					
					index = wms_order.indexOf("wms_Pipeline_age_15");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index);
				}
			}
			else if (age == "Main-pipe-age-15") {
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_Main_pipe_age_15);
					toplevel++;
					wms_order.push("wms_Main_pipe_age_15");
				}
				else {
					index = wms_order.indexOf("wms_Main_pipe_age_15");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index);
				}
			}
			else if (age == "distribution-pipe-age-15") {
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_distribution_pipe_age_15);
					toplevel++;
					wms_order.push("wms_distribution_pipe_age_15");
				}
				else {
					index = wms_order.indexOf("wms_distribution_pipe_age_15");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index);
				}
			}
			else if (age == "pipe-ac-age-15")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_AC_age_15);
					toplevel++;
					wms_order.push("wms_pipe_AC_age_15");
				}
				else {
					index = wms_order.indexOf("wms_pipe_AC_age_15");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index);
				}
			}
			else if (age == "pipe_line_age_25")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_Pipe_line_age_15_to_25);
					toplevel++;
					wms_order.push("wms_Pipe_line_age_15_to_25");
				}
				else {
					index = wms_order.indexOf("wms_Pipe_line_age_15_to_25");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index);
				}
			}
			else if (age == "Main-pipe-age-25")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_Main_Pipe_age_15_to_25);
					toplevel++;
					wms_order.push("wms_Main_Pipe_age_15_to_25");
				}
				else {
					index = wms_order.indexOf("wms_Main_Pipe_age_15_to_25");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "distribution-pipe-age-25")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_distribution_pipe_age_15_to_25);
					toplevel++;
					wms_order.push("wms_distribution_pipe_age_15_to_25");
				}
				else {
					index = wms_order.indexOf("wms_distribution_pipe_age_15_to_25");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "pipe-ac-age-25")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_AC_age_15_to_25);
					toplevel++;
					wms_order.push("wms_pipe_AC_age_15_to_25");
				}
				else {
					index = wms_order.indexOf("wms_pipe_AC_age_15_to_25");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "pipe_line_age_30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_line_age_25_to_30);
					toplevel++;
					wms_order.push("wms_pipe_line_age_25_to_30");
				}
				else {
					index = wms_order.indexOf("wms_pipe_line_age_25_to_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "Main-pipe-age-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_Main_pipe_age_25_to_30);
					toplevel++;
					wms_order.push("wms_Main_pipe_age_25_to_30");
				}
				else {
					index = wms_order.indexOf("wms_Main_pipe_age_25_to_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "distribution-pipe-age-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_distribution_pipe_age_25_to_30);
					toplevel++;
					wms_order.push("wms_distribution_pipe_age_25_to_30");
				}
				else {
					index = wms_order.indexOf("wms_distribution_pipe_age_25_to_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "pipe-ac-age-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_ac_age_25_to_30);
					toplevel++;
					wms_order.push("wms_pipe_ac_age_25_to_30");
				}
				else {
					index = wms_order.indexOf("wms_pipe_ac_age_25_to_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "pipe-line-age-over-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_line_age_over_30);
					toplevel++;
					wms_order.push("wms_pipe_line_age_over_30");
				}
				else {
					index = wms_order.indexOf("wms_pipe_line_age_over_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "Main-pipe-age-over-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_Main_pipe_age_over_30);
					toplevel++;
					wms_order.push("wms_Main_pipe_age_over_30");
				}
				else {
					index = wms_order.indexOf("wms_Main_pipe_age_over_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "distribution-pipe-age-over-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_distribution_pipe_age_over_30);
					toplevel++;
					wms_order.push("wms_distribution_pipe_age_over_30");
				}
				else {
					index = wms_order.indexOf("wms_distribution_pipe_age_over_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
			else if (age == "pipe-ac-age-over-30")
			{
				if($(this).prop("checked")) {
					map.overlayMapTypes.insertAt(toplevel, wms_pipe_ac_age_over_30);
					toplevel++;
					wms_order.push("wms_pipe_ac_age_over_30");
				}
				else {
					index = wms_order.indexOf("wms_pipe_ac_age_over_30");
					map.overlayMapTypes.removeAt(index);
					toplevel--;		
					ShiftArray(index); 
				}
			}
		
	});
	
	$(function() {
		hideAddressBar();
	});
	$("#gsearch_button").on("click", function(){							
		var address = $('#gsearch_address').val();					
		geocoder.geocode({											
			'address': address
		}, 
		function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				clearOverlays();
				map.setCenter(results[0].geometry.location);
				var marker = new google.maps.Marker({
					map: map,
					position: results[0].geometry.location
				});
				markersArray.push(marker);							//add search results to array max 5 
				try {
					var marker2 = new google.maps.Marker({
						map: map,
						position: results[1].geometry.location
					});
					markersArray.push(marker2);
					
					var marker3 = new google.maps.Marker({
						map: map,
						position: results[2].geometry.location
					});
					markersArray.push(marker3);
					var marker4 = new google.maps.Marker({
						map: map,
						position: results[3].geometry.location
					});
					markersArray.push(marker4);
					var marker5 = new google.maps.Marker({
						map: map,
						position: results[4].geometry.location
					});
					markersArray.push(marker5);
				}
				catch(error){
					// onsole.log(error);
				}
				map.setCenter(results[0].geometry.location);
				if(map.getZoom() < 17)
                                    map.setZoom(17);
				
			} else {												//no popup results found
				$( "#noResults_popup" ).popup( "open" );
				// console.log("No results found");
			}
		});
	});
	
	$("#logout").click(function() {									//logout session
		if (confirm('ยืนยันการออกจากระบบ') == true) {
			// alert('test');
			$.ajax({
				type: "POST",
				url: "Destroysession.php",
				data: {
					sure: "1"
				},
				statusCode: {
					404: function() {
						alert("??????????????????");
					},
					200: function() {
						// alert("?????????");
					}
				}
			}).done(function(data) {
				if (data == 1) {
					window.location = "LoginForm.php";
				}
			});
		}
	});
	$( "input.gistda" ).on( "click", function() {
		var selectedLayer = $(this).val();	
		if ($(this).prop("checked"))
		{
			//var path = [];
			GetCarPath();
			car_timer = setInterval("GetCarPath()", 300000);		// Refresh every 5 minutes
		}
		else	
		{
			clearInterval(car_timer);
			//car_path.setMap(null);
			car_position.setMap(null);
		}
	});
	$( "input.WMS" ).on( "click", function() {
		var selectedLayer = $(this).val();			
		if ($(this).prop("checked"))
			OverlayWMS(wmslayers[selectedLayer]);
		else	
			RemoveWMS(wmslayers[selectedLayer]);
	});
	$('.overflow_popup').on({									// set height of popup		
	  popupbeforeposition: function() {
		var maxHeight = $(window).height() - 50;		
		$('.overflow_popup').css('max-height', maxHeight + 'px');
	  }
	});
	
	$("#report_popup").on({
		popupbeforeposition: function() {						// resize report
																// popup
			$("#report_popup iframe")
				.attr( "width", $(window).width() - 100 )
                .attr( "height", $(window).height() - 100);
		}			
	});		
	// on stolen meter move
	// overlay stolen meter layer if the checkbox is checked else remove layer
	$( "#month_slider").on('slidestop', function( event ) {
		// update stolen meter label
		UpdateStolenMeterLabel();
		if ($("input.stolenmeter_slider").prop("checked"))
		{
                    OverlayStolenMeter($("input.stolenmeter_slider").prop("checked"));    
		}
	});
	// on stolen meter checkbox change
	// overlay stolen meter WMS if checkbox is checked
	$("input.stolenmeter_slider").on( "click", function() {
		OverlayStolenMeter($("input.stolenmeter_slider").prop("checked"));
	});
	// on chlorine slider move
	// overlay chlorine layer if the checkbox is checked else remove layer
	$( "#chlorine_month_slider").on('slidestop', function( event ) {
		// update chlorine label
		UpdateChlorineLabel();
		OverlayChlorine($("input.chlorine_slider").prop("checked"));
	});
	// on chlorine checkbox change
	// overlay chlorine contour if checkbox is checked
	$("input.chlorine_slider").on( "click", function() {
		OverlayChlorine($("input.chlorine_slider").prop("checked"));
		
	});
	
	$("a#EserviceSetDate").click(function( event ) {
		//if ($('#checkbox-select-eservice').prop('checked') == true)
		//{
			//$('#checkbox-select-eservice').prop('checked', true);
			eserviceStatus = $("#checkbox-select-eservice").prop("checked");
			isEserviceDatePickerClicked = true;
			if (eserviceStatus)
			{
				setTimeout(function(){
					callEserviceDatePicker();
				}, 50);
				$( '#waterresource_popup' ).popup("close");
				
				//$( '#waterresource_popup' ).on( 'popupafterclose', function() {
				//	setTimeout( function(){ 
				//		callEserviceDatePicker();
				//	}, 10);
				//});
			}
		//}
		//else	
			//$('#checkbox-select-eservice').prop('checked', false);
		
	});
	//$("a[href$='.jpg']").click(function(){
	//	this.attr("data-rel", "popup");
	//	alert("link clicked");
	//});
	//$("a", ".dialogpopup").click(function(){alert("clicky")});
	var toggle = 0;
	$("a#gis_search_button").click(function( event ) {
            var btn_text = $(this).text();
            if(btn_text == "ค้นหาทะเบียนผู้ใช้น้ำ") {               
               var gis_search = $("#gis_search").val();            
               var nameBranchGIS = $("#list_branch[name=list_branch]").val();      
               //console.log(gis_search, nameBranchGIS);
               if(gis_search.length <= 0 || nameBranchGIS.length <= 0) {              
               }
               else {                
                   $.ajax({
                       url: "ajax/queryServiceGIS.php",
                       data:{ACC_ID : gis_search,BRANCH : nameBranchGIS},
                       success : function (data) {
                           var acc_data = $.parseJSON(data);
                          // console.log(acc_data);
                           //console.log("acc_data.features.length", acc_data.features.length);
                           if(acc_data.features.length == 0){
                               $("p.p_gis_search").show('2000').delay(4000).hide('slow');
                           }else{                          
                               ClearOverlay_BY_JIK(markerGISsreach);
                               directionsDisplay.setDirections({ routes: [] });

                               var latitude = acc_data.features[0].geometry.y;
                               var longitude = acc_data.features[0].geometry.x;

                               //var convertSpatial = convertToLatLng(longitude,latitude);
                               //var lng = convertSpatial.Lng;
                               //var lat = convertSpatial.Lat;

                               latlngGISSearch = new google.maps.LatLng( latitude, longitude );

                               var GIS_Sreach = new google.maps.Marker({
                                   map: map,
                                   position: latlngGISSearch,
                                   icon:"image/images/home.png"
                               });
                               markerGISsreach.push(GIS_Sreach);

                               map.setCenter(latlngGISSearch);
                               map.setZoom(17);                            

                               google.maps.event.addListener(GIS_Sreach, 'click', function() {
                                   if (gisSearchInfo){
                                       gisSearchInfo.close();
                                   }
                                   var gisSearchContent = "target";
                                   gisSearchInfo = new google.maps.InfoWindow({
                                           content : gisSearchContent,
                                           maxWidth: 1000,
                                           maxHeigth: 1000							 
                                   });	
                                   gisSearchInfo.open(map, this);						
                               });              
                                $("a#gis_search_button .ui-btn-text").text("Remove");
                               if($('#gis_search_checkbox').prop('checked'))   
                                    getLocationRoute();                                                                  
                           }
                       }
                   });
               }
            }
            else {
                $("a#gis_search_button .ui-btn-text").text("ค้นหาทะเบียนผู้ใช้น้ำ");
                ClearOverlay_BY_JIK(markerGISsreach);
                directionsDisplay.setDirections({ routes: [] });
            }
        });
        function getLocationRoute(){
            if(navigator.geolocation ) {
                navigator.geolocation.getCurrentPosition(gpssuccessCallback);             
            }
        }
        function gpssuccessCallback(position) {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            calcRoute(lat,lng);
            
        }
        function calcRoute(lat,lng) {
            var request = {
                origin: new google.maps.LatLng(lat, lng),
                destination: latlngGISSearch,
                travelMode: google.maps.TravelMode.DRIVING
                
            };            
            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    var route = response.routes[0];                    
			for (var i = 0; i < route.legs.length; i++) {                            
                            addMarkerRounte(route.legs[i].start_location);
                            //addMarkerRounte(route.legs[i].end_location);
			}
                    directionsDisplay.setDirections(response);
                }
            });
        }    
        function addMarkerRounte(position) {
            var markers = new google.maps.Marker({
		position: position, 
		map: map,
		icon: "image/images/iamhere.png"
            });
            markerGISsreach.push(markers);
            
            var gisSearchContent = "iamhere";
            google.maps.event.addListener(markers, 'click', function(event) {
                if(gisSearchInfo) gisSearchInfo.close();
                gisSearchInfo = new google.maps.InfoWindow({
                    content : gisSearchContent,
                    maxWidth: 1000,
                    maxHeigth: 1000							 
                });	
                gisSearchInfo.open(map, this);		
            });
        }    
        function convertToLatLng(mercX, mercY) {     
            var rMajor = 6378137; //Equatorial Radius, WGS84
            var shift  = Math.PI * rMajor;
            var lng    = mercX / shift * 180.0;
            var lat    = mercY / shift * 180.0;
            lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0);

            return { 'Lng': lng, 'Lat': lat };
        }
        $( "input.vector" ).on( "click", function(e) {
            var selectedLayer = $(this).val();
            if(selectedLayer == "Condo") {
                if($(this).prop("checked")) 
                    HomeThailand(selectedLayer);
                else
                    ClearOverlay_BY_JIK(Condo);
            }
            else if(selectedLayer == "SingleHouse"){
                if($(this).prop("checked")) 
                    HomeThailand(selectedLayer);
                else
                    ClearOverlay_BY_JIK(SingleHouse);
            }
             else if(selectedLayer == "Townhouse"){
                if($(this).prop("checked")) 
                    HomeThailand(selectedLayer);
                else
                    ClearOverlay_BY_JIK(Townhouse);
            }
            
        });        
});